<?php


/*
*
*   Excalibur Content Management System
*   Copyright © 2008 Egor "Sontan" Kuryanovich
*
*   Based on Explay Engine v2.0 by Golovdinov Alexander
*
*   Official site: www.excms.ru
*   Contact e-mail: support@excms.ru
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
*/


if ($EXCMS != 'work') {
	header ('Location: ../../index.php');
	exit;
}

function expl_hash($str)
{
	if (function_exists('sha1')) return sha1($str); 
	elseif (function_exists('mhash')) return bin2hex(mhash(MHASH_SHA1, $str));
	else return md5($str);
}

function _get ($par, $option = 'option') 
{
	if (isset($_GET['option'])) {
		$string = htmlspecialchars (trim ($_GET[$option]));
		$string = explode ('/', $string);
		$arr = array ();
		
		for ($i=1; $i<=count($string); $i++) if (strlen ($string[$i-1]) > 0) $arr[$i] = $string[$i-1];
		
		if (isset($arr[$par])) return $arr[$par];
		else return "";
	}
	else return "";
}

function clear_danger_html ($string) 
{
	$string = preg_replace ("#onclick=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onmouseover=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onmouseout=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onmousedown=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onmouseup=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onselect=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onfocus=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onblur=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onload=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onkeydown=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onkeyup=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#ondblclick=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onunload=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onmouseup=[\"|\'](.+?)[\"|\']#is", "", $string);
	$string = preg_replace ("#onsubmit=[\"|\'](.+?)[\"|\']#is", "", $string);
	
	return $string;
}

function n2br ($string) 
{
	$string = str_replace ("\n", '<br />', $string);
	$string = str_replace ("\r", '', $string);
	return $string;
}

function input_video ($string) 
{
	$string = preg_replace('#\<youtube>(.+?)</youtube>#is', 
							'<object width="425" height="355">
									<param name="movie" value="1"></param>
									<param name="wmode" value="transparent"></param>
									<embed src="1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed>
							</object>', $string);	
			
	$string = preg_replace('#\<rutube>(.+?)</rutube>#is', 
							'<OBJECT width="400" height="353">
								<PARAM name="movie" value="1" />
								<PARAM name="wmode" value="window" />
								<PARAM name="allowFullScreen" value="true"></PARAM>
								<EMBED src="1" type="application/x-shockwave-flash" wmode="window" width="400" height="353" allowFullScreen="true" />
							</OBJECT>', $string);
	
	return $string; 
}

function replace_symbols ($string) 
{ 
	$string = str_replace ('«', '&laquo;', $string);
	$string = str_replace ('»', '&raquo;', $string);
	$string = str_replace ('—', '&mdash;', $string);
	$string = str_replace ('©', '&copy;', $string);
	$string = str_replace (' - ', '&nbsp;&mdash; ', $string);
	
	return $string;
}

function print_comments ($category, $idi, $url, $sort = "") 
{
	global $GLOBAL_USER, $SITE, $template, $db;

	if (isset($_GET['page_comments']) && $_GET['page_comments'] != "0") 
		$start = (intval ($_GET['page_comments']) - 1) * $SITE['site_comments'];
	else 
		$start = 0;

	$comments = array ();
	
	$query = $db->query ("SELECT comm.*, usr.user_avatar, usr.user_name FROM ".DB_PEREFIX."_comments AS comm
		LEFT JOIN (SELECT user_id, user_name, user_avatar FROM ".DB_PEREFIX."_users) AS usr ON usr.user_id = comm.com_uid
		WHERE com_category = '$category' AND com_idi = '$idi' ORDER BY com_id $sort");
	if ($db->num_rows ($query) > 0) 
	{
			
		$count = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_comments WHERE com_category = '$category' AND com_idi = '$idi'"));
		//print "\n<a name=\"comments\"></a>\n<div id=\"comments_div\">\n";
		
		while ($com = $db->fetch_array ($query)) 
		{
			$comments[$com['com_parent']][] = array ($com['com_id'], $com['com_uid'], $com['com_author'], $com['com_mail'], $com['com_text'], $com['com_date'], $com['user_ip'], $com['user_name'], $com['user_avatar'], $com['com_rating'], $com['com_voters']);
		}
	
		show ($comments[0], $comments, $url, $category, $idi);
	}
}


function show ($arr, $comments, $url, $module, $idi, $level = 0) 
{
	if ($level >= 300) 
		$level -= 50;

	foreach ($arr as $comm) 
	{
		list ($id, $uid, $author, $mail, $text, $date, $ip, $uname, $uavatar, $rating, $voters) = $comm;
		display_comment ($id, $uid, $author, $mail, $text, $date, $ip, $level, $url, $module, $idi, $uname, $uavatar, $rating, $voters);
		if (isset ($comments[$id])) show ($comments[$id], $comments, $url, $module, $idi, $level+50);
	}
}

function display_comment ($id, $uid, $author, $mail, $text, $date, $ip, $level, $url, $module, $idi, $uname, $uavatar, $rating, $voters) 
{
	global $SITE, $template, $GLOBAL_USER, $db;
	
	$author = stripslashes($author);
   	$text = replace_symbols(n2br((stripslashes($text))));
	$img = '';
	
	if ($mail != '') 
	{
		$mail = str_replace ('mailto:', '', $mail);
		$name = '<a href="mailto:'.$mail.'">'.$author.'</a>';
	}
	else
	{
		$name = $author;
	}
	
	if ($uid != '' && $uid != 0) 
	{
		//$user = $db->fetch_array ($db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_id = '$uid'"));
		//$uname = $user['user_name'];
		$name = '<a href="/users/'.$uid.'.html">'.$uname.'</a>';
		//if ($user['user_avatar'] != "") $avatar = "/images/avatars/".$user['user_avatar'];

		// Если аватар не задан то устанавливаем стандартный
		if ($uavatar != '') 
			$avatar = '/images/avatars/'.$uid.'.jpg';
		else 
			$avatar = '/images/avatars/noavatar.gif';

		$img = '<a href="/users/'.$uid.'.html"><img src="'.$avatar.'" title="Аватар для '.$uname.'" /></a>';
	}
	
	// Скрываем комментарий если рэйтинг меньше 5
	if ($rating < -5 )
	{
		$text = '<a href="#" class="" onClick="return show_hidden_comm('.$id.');" id="hidden_l'.$id.'">раскрыть комментарий</a>
					<span style="display: none;" id="hidden_c'.$id.'">'.$text.'</span>';
    }
	
	// Выводим рэйтинг с цветовым кодированием
	if ($rating == 0) 
		$rating = '<span class="com_rating_zero">0</span>';
	elseif ($rating > 0) 
		$rating = '<span class="com_rating_plus">+'.$rating.'</span>';
	else 
		$rating = '<span class="com_rating_minus">'.$rating.'</span>';
		


	// Проверяем голосовал ли пользователь за комментарий
	$vote = false;
	$voters = explode (',', $voters);
	foreach ($voters as $v) if ($GLOBAL_USER['user_id'] == trim($v)) $vote = true;
	
	// Проверяем на возможность проголосовать
	(is_registered () && my_karma() >= 0 && $vote == false && $uid != $GLOBAL_USER['user_id']) 
		? $rating .= str_replace ('{id}', $id, get_element ('{comm_rating_change}', '{/comm_rating_change}')) 
		: $rating .= get_element ('{comm_rating_cant}', '{/comm_rating_cant}');
	
	($uid != "" && $uid != 0) 
		? $template->set_var ("{USER_ID}", $uid) 
		: $template->set_var ("{USER_ID}", ""); 
	
	
	$template->set_var ('{NAME}', $name);
	$template->set_var ('{COMMENT_ID}', $id);
	$template->set_var ('{DATE}', format_time($date));
	$template->set_var ('{IP}', $ip);
	$template->set_var ('{MODULE}', $module);
	$template->set_var ('{AVATAR}', $img);
	$template->set_var ('{BODY}', replace_symbols(n2br(($text))));
	$template->set_var ('{BOTTOM}', $bottom);
	$template->set_var ('{LEVEL}', $level);
	$template->set_var ('{MODULE}', $module);
	$template->set_var ('{IDI}', $idi);
	$template->set_var ('{RATING}', $rating);
	
	print $template->display ('comment.tpl');
}

function delete_comment ($id) 
{
	global $db;
	$delete = $db->query ("DELETE FROM ".DB_PEREFIX."_comments WHERE com_id = '$id'");
	if ($delete) site_message ('Комментарий удален!');
	else site_error ('Комментарий не был удален!');
}


function add_comment ($name, $mail, $body, $category, $id, $code) 
{
	global $SITE, $GLOBAL_USER, $db, $template;
	
	$allowed_tags = array('a','blockquote','i','em','b','strong',
							'u','ul','ol','li','sup','table','tr','td',
							's','strike','font','img','nobr','abbr',
							'acronym','pre','code','br');
	$allowed_string = '';

	foreach ($allowed_tags as $tag) 
		$allowed_string .= '<'.$tag.'>';
	
	if ($SITE['allow_comments'] == 'yes') 
	{
		if (my_karma() > '-10') 
		{
			$uid = '0';
			if ($GLOBAL_USER['user_id'] != '') $uid = $GLOBAL_USER['user_id'];
			$body = strip_tags ($body, $allowed_string);
			$body = replace_symbols ($body);
			$name = strip_tags ($name);
			$error = '';
			$mail = str_replace ('mailto:', '', $mail);
			$mail = trim($mail);
			$parent = 0;
			

		
			if (isset($_POST['parent'])) 
			{
				if (is_registered()) 
				{ 
					$parent = intval($_POST['parent']); 
					$SITE['bot_protect'] = ''; 
				}
				else 
				{ 
					$error .= '<li>Вы не можете отвечать на комментарии!'; 
					$parent = 0; 
				}
			}
		
			
			if ($body == '') 
				$error .= '<li>Не заполнено поле текста!';

			if (!is_registered()) 
			{
				if ($name == '') 
					$error .= '<li>Не заполнено имя!';

				if ($mail != '') 
				{
					if (!eregi('^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,4}\$',$mail)) 
						$error .= '<li>Неверно заполнен e-mail!';
				}
			}
		
			if ($SITE['bot_protect'] == 'yes' && !is_registered()) 
			{
				if ($code != $_SESSION['secret_code'] || $code == '') $error .= '<li>Неверный код!';
			}
	
			if (mb_strlen($name) > 25) $error .= '<li>Имя слишком длинное!';
			if (mb_strlen($mail) > 40) $error .= '<li>E-mail слишком длинный!';
			if (mb_strlen($body) > 1000) $error .= '<li>Текст слишком длинный!';

	
			// FIXME: Исправить на count()
			$timer = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_comments WHERE com_category = '$category' AND com_idi = '$id' AND com_parent = 0 AND user_ip = '".$_SERVER['REMOTE_ADDR']."' AND com_date > ".(time()-300) ));

			if ($timer > 0) 
				$error .= '<li>Вы не можете оставлять комментарии так часто!';
			
			if ($error == '') 
			{	
				$insertc = "INSERT INTO ".DB_PEREFIX."_comments VALUES (0, '$uid', '$category', '$id', '".strip_tags($name)."', '".strip_tags($mail)."', '$body', '".time()."', '".$_SERVER['REMOTE_ADDR']."', '$parent', 0, '')";

				if ($db->query($insertc)) 
				{
					// Очищаем кэш блока комментариев
					clear_cached('excl_last_comments.php');
					
					// Если отвечаем на комментарий
					if (isset($_POST['parent'])) 
					{
						// Загружаем данные пользователя на комментарий которого отвечаем
						$query = $db->query ("SELECT a.art_header, a.art_id, u.user_id, u.user_name, u.user_email, c.com_text 
						FROM ".DB_PEREFIX."_users AS u
						JOIN ".DB_PEREFIX."_comments AS c ON (u.user_id = c.com_uid)
						JOIN ".DB_PEREFIX."_articles AS a ON (c.com_idi = a.art_id)					
						WHERE com_id ='$parent';");
						$parent = $db->fetch_array($query);
					
						// Если отвечаем не на свой комментарий
						if ($GLOBAL_USER['user_id'] != $parent['user_id'] )
						{
							$url = 'http://'.$_SERVER['HTTP_HOST'].'/';
							$template->set_var ("{NAME}", $parent['user_name']);
							$template->set_var ("{OLDTEXT}", '<i>'.$parent['com_text'].'</i>');								
							$template->set_var ("{NEWTEXT}", '<i>'.$body.'</i>');
							$template->set_var ("{USER}",
							'<a href="'.$url.'users/'.$GLOBAL_USER['user_id'].'.html">'.$GLOBAL_USER['user_name'].'</a>');					
							$template->set_var ("{TOPIC}",
							'<a href="'.$url.'articles/'.$parent['art_id'].'.html">&quot;'.$parent['art_header'].'&quot;</a>');
							$template->set_var ("{SITE}", '<a href="'.$url.'">'.$SITE['site_name'].'</a>');					
							$body = $template->display("mail/new_comment.tpl");

							// Отсылаем оповещение
							send_mail ($parent['user_email'], 'Ответ на ваш комментарий к теме ['.$parent['art_header'].']', n2br($body));
						}
					}
					// Если отвечае на статью
					else
					{
						// Загружаем данные пользователя на статью которого отвечаем
						$query = $db->query ("SELECT a.art_header, a.art_id, u.user_id, u.user_name, u.user_email
						FROM ".DB_PEREFIX."_articles AS a
						JOIN ".DB_PEREFIX."_users AS u ON (a.art_author = u.user_id)					
						WHERE art_id ='$id';");
						$parent = $db->fetch_array($query);
					
						// Если отвечаем не на свой же пост
						if ($GLOBAL_USER['user_id'] != $parent['user_id'] )
						{
							$url = 'http://'.$_SERVER['HTTP_HOST'].'/';
							$template->set_var ("{NAME}", $parent['user_name']);					
							$template->set_var ("{NEWTEXT}", '<i>'.$body.'</i>');
							$template->set_var ("{USER}",
							'<a href="'.$url.'users/'.$GLOBAL_USER['user_id'].'.html">'.$GLOBAL_USER['user_name'].'</a>');					
							$template->set_var ("{TOPIC}",
							'<a href="'.$url.'articles/'.$parent['art_id'].'.html">&quot;'.$parent['art_header'].'&quot;</a>');
							$template->set_var ("{SITE}", '<a href="'.$url.'">'.$SITE['site_name'].'</a>');					
							$body = $template->display("mail/new_artcomment.tpl");

							// Отсылаем оповещение
							send_mail ($parent['user_email'], 'Ответ на вашу статью ['.$parent['art_header'].']', n2br($body));				
					
						}
					}
					
					site_message ('Комментарий добавлен!');
					
				}
				else 
					site_error ('Ошибка добавления комментария!');
			}
			else 
				site_error ($error);

			$SITE['bot_protect'] == 'yes';
		}
		else 
			site_error ('У Вас настолько низкая карма, что вы не можете добавлять комментарии.');
	}
	else 
		site_error ('На сайте нельзя добавлять комментарии!');
}

function is_cached ($filename, $time) 
{
	$file = "include/cache/$filename";
	if (file_exists ($_SERVER['DOCUMENT_ROOT'].'/'.$file)) 
	{
		if (filemtime ($_SERVER['DOCUMENT_ROOT'].'/'.$file) > (time() - $time)) return true;
		else return false;
	}
	else return false;
}

function cache_file ($filename, $content) 
{
	$file = "include/cache/$filename";
	clear_cached($filename);
	
	$cache_file = fopen ($_SERVER['DOCUMENT_ROOT'].'/'.$file, 'w');
	flock ($cache_file, LOCK_EX);
	fwrite ($cache_file, $content);
	flock ($cache_file, LOCK_UN);
	fclose ($cache_file);
}

function clear_cached($filename)
{
	$file = 'include/cache/'.$filename;
	if (file_exists ($file)) unlink ($file);
}

function my_karma () 
{
	global $GLOBAL_USER;
	if (!is_registered()) return 0;
	elseif (is_admin()) return 99999;
	else return $GLOBAL_USER['user_karma'];
}

function user_status ($id) 
{
	global $theme, $db;
	$get_user = $db->query ("SELECT * FROM ".DB_PEREFIX."_sessions WHERE uid = '$id'");
	if ($db->num_rows ($get_user) == 1) {
		return "<img src=\"/themes/$theme/images/online.gif\" title=\"Пользователь on-line\" align=\"middle\" /> ";
	}
	else return "<img src=\"/themes/$theme/images/offline.gif\" title=\"Пользователь off-line\" align=\"middle\" /> ";
}


function past_pages ($start, $number, $count, $url, $get_start_name = 'page', $after_url_arr = array(), $admin_panel = false) 
{	
	$g_start = $start;
	$pages = '';
	$p_count = ($start / $number) + 1;
	
	$after_url = '';
	// Обрабатываем список элементов поиска
	foreach ($after_url_arr as $element)
	{
		($after_url == '')
			? $after_url .= '?'
			: $after_url .= '&';
			
		$after_url .= $element;
	}
	
	if ($count > $number) 
	{
		if ($g_start > 0) 
		{ 
			($admin_panel == true) 
				? $pages .= '<a href="'.$url.'page='.( ($g_start - $number) / $number + 1).'">&#8592;</a>' 
				: $pages .= '<a href="'.$url.$get_start_name.(($g_start - $number) / $number + 1).'/'.$after_url.'">&#8592;</a>'; 
		}
		
		if ($start - $number >= 0) 
		{
			$start_back = $start;
			
			$p_count_back = 1;
			$back_s = 0 - $number;
			$break = $start_back / $number;
			$i = 1;
			
			if ($start_back / $number >= 5)
			{
				($admin_panel == true)	
					? $pages .= '<a href="'.$url.'page=1">1</a>' 
					: $pages .= '<a href="'.$url.$get_start_name.'1/'.$after_url.'">1</a> ... ';
				$back_s = $number - ($number - 4);
				$p_count_back = $start_back / $number - 3;
				$break = 5;
			}
			
			while ($start_back - $number >= 0) 
			{
				if ($break == 5) 
					if ($i >= $break) break;
				else 
					if ($i > $break) break;
				
				if ($back_s + $number >= $start) break;
				
				if ($break != 5) 
					($admin_panel == true) 
						? $pages .= '<a href="'.$url.'page='.(($back_s + $number) / $number + 1).'">'.$p_count_back.'</a>'
						: $pages .= '<a href="'.$url.$get_start_name.(($back_s + $number)/$number + 1).'/'.$after_url.'">'.$p_count_back.'</a>';
				else 
					($admin_panel == true) 
						? $pages .= '<a href="'.$url.'page='.$p_count_back.'">'.$p_count_back.'</a>'
						: $pages .= '<a href="'.$url.$get_start_name.$p_count_back.'/'.$after_url.'">'.$p_count_back.'</a>';
				
				$p_count_back++;
				$back_s = $back_s + $number;
				$i++;
			}
		}
		$pages .= '<b>'.$p_count.'</b>';
		if ($start + $number < $count) 
		{	
			$break = ($count - $start) / $number;
			$i = 1;			
			
			if ($break > 4) $break = 5;
			
			while ($start + $number < $count) 
			{
				//if ($i >= $break) break;
				
				if ($start + $number > $count) break;
				$p_count++;
				if ($i < $break) ($admin_panel == true)
					? $pages .= '<a href="'.$url.'page='.(($start + $number) / $number+ 1).'">'.$p_count.'</a>'
					: $pages .= '<a href="'.$url.$get_start_name.(($start + $number) / $number + 1).'/'.$after_url.'">'.$p_count.'</a>';
				
				$last_page = (($start + $number) / $number ) + 1;
				$start = $start + $number;
				$i++;
			}
			if ($break == 5) 
				($admin_panel == true) 
					? $pages .= ' ... <a href="'.$url.'page='.$last_page.'">'.$last_page.'</a>'
					: $pages .= ' ... <a href="'.$url.$get_start_name.$last_page.'/'.$after_url.'">'.$last_page.'</a>';
		}
		if ($count > $g_start + $number) 
		{ 
			($admin_panel == true) 
				? $pages .= '<a href="'.$url.'page='.(($g_start + $number) / $number + 1).'">&#8594;</a>' 
				: $pages .= '<a href="'.$url.$get_start_name.(($g_start + $number) / $number + 1).'/'.$after_url.'">&#8594;</a>'; 
		}
		
		($admin_panel == true) 
			? $return = '<center>Всего: '.$count.', Страницы: '.$pages.'</center>' 
			: $return = '<div class="pages">Страницы: '.$pages.'</div>';
		return $return;
	}
}




function is_registered () 
{
	global $GLOBAL_USER;
	if ($GLOBAL_USER['user_id'] > 0) return true;
	else return false;
}

function is_admin () 
{
	global $GLOBAL_USER;
	if ($GLOBAL_USER['user_group'] == 'admin') return true;
	else return false;
}

function is_moderator () 
{
	global $GLOBAL_USER;
	if ($GLOBAL_USER['moderator'] == 1) return true;
	else return false;
}

function format_time ($string) 
{
	global $SITE;
	
	$today = intval (date('H')) * 3600 + intval(date('i')) * 60 + intval(date('s'));
	
	// it was for a long time
	if (date ('Y', $string) != date ('Y')) $date = date ('d.m.Y H:i', $string);
	
	// it was for a hour ago
	elseif ((time() - $string) < 3600) {
		$date = count_smth ((date ('i', (time() - $string))), array ('минуту', 'минуты', 'минут')).' назад';
	}
	
	elseif ((time() - $string) < $today) {
		$date = 'сегодня в '.date('H:i', $string);
	}
	
	// default variant
	else {
		$date = date ($SITE['date_format'], $string);
		$date = str_replace ('January', 'Января', $date);
		$date = str_replace ('February', 'Февраля', $date);
		$date = str_replace ('March', 'Марта', $date);
		$date = str_replace ('April', 'Апреля', $date);
		$date = str_replace ('May', 'Мая', $date);
		$date = str_replace ('June', 'Июня', $date);
		$date = str_replace ('July', 'Июля', $date);
		$date = str_replace ('August', 'Августа', $date);
		$date = str_replace ('September', 'Сентября', $date);
		$date = str_replace ('October', 'Октября', $date);
		$date = str_replace ('November', 'Ноября', $date);
		$date = str_replace ('December', 'Декабря', $date);
	}
	return $date;
	return 'выключено';
}

function past_smiles ($name) 
{
	return "";
}

function print_edit ($name) 
{
	global $GLOBAL_USER;
	$edit = '<div style="width:100%;background-image:url(/images/edit/bg.gif);font-size:1pt;padding:0px;margin-bottom:0px;border:silver 1px solid">
	<img onclick="AddText_'.$name.'(\'b\', \'b\');" border="0" src="/images/edit/b.gif" title="Жирный">
	<img onclick="AddText_'.$name.'(\'i\', \'i\');" border="0" src="/images/edit/i.gif" title="Курсив">
	<img onclick="AddText_'.$name.'(\'s\', \'s\');" border="0" src="/images/edit/s.gif" title="Зачеркнутый">
	<img onclick="AddText_'.$name.'(\'u\', \'u\');" border="0" src="/images/edit/u.gif" title="Подчеркнутый">
	<img onclick="AddText_'.$name.'(\'l\', \'l\');" border="0" src="/images/edit/l.gif" title="Выровнить: лево">
	<img onclick="AddText_'.$name.'(\'c\', \'c\');" border="0" src="/images/edit/c.gif" title="Выровнить: по центпу">
	<img onclick="AddText_'.$name.'(\'r\', \'r\');" border="0" src="/images/edit/r.gif" title="Выровнить: право">
	<img onclick="AddText_'.$name.'(\'url=http://\', \'url\');" border="0" src="/images/edit/link.gif" title="Ссылка">
	<img onclick="AddText_'.$name.'(\'mail\', \'mail\');" border="0" src="/images/edit/email.gif" title="E-mail адрес">
	<img onclick="AddText_'.$name.'(\'li\', \'li\');" border="0" src="/images/edit/li.gif" title="Список">
	<img onclick="AddText_'.$name.'(\'q\', \'q\');" border="0" src="/images/edit/quote.gif" title="Цитата">
	<img onclick="AddText_'.$name.'(\'color=\', \'color\');" border="0" src="/images/edit/color.gif" title="Цвет">';
	if (is_admin()) $edit .= '<img onclick="AddText_'.$name.'(\'page=\', \'page\');" border="0" src="/images/edit/page.gif" title="Ссылка на статью">
	<img onclick="AddText_'.$name.'(\'img\', \'img\');" border="0" src="/images/edit/img.gif" title="Картинка">
	<img onclick="insertText_'.$name.'(\'«»\');" border="0" src="/images/edit/quotes.gif" title="Кавычки">
	<img onclick="insertText_'.$name.'(\'—\');" border="0" src="/images/edit/dash.gif" title="Тире">
	<img onclick="insertText_'.$name.'(\'©\');" border="0" src="/images/edit/copyr.gif" title="Символ копирайта">
	<img onclick="insertText_'.$name.'(\'®\');" border="0" src="/images/edit/reg.gif" title="Символ зарегистрированного товарного знака">
	<img onclick="insertText_'.$name.'(\'™\');" border="0" src="/images/edit/tm.gif" title="Символ торговой марки">
	<img onclick="insertText_'.$name.'(\'&rarr;\');" border="0" src="/images/edit/right.gif" title="Стрелка вправо">
	<img onclick="insertText_'.$name.'(\'&larr;\');" border="0" src="/images/edit/left.gif" title="Стрелка влево">
	<img onclick="insertText_'.$name.'(\'§\');" border="0" src="/images/edit/par.gif" title="Знак параграфа">';
	$edit .= "</div>";
	return $edit;
}

function insert_script ($name) 
{
	$script = "<script type=text/javascript>
var editBody_$name = document.record.$name;
function insertText_$name(theText_$name) 
{
	if (editBody_$name.createTextRange && editBody_$name.curPos) editBody_$name.curPos.text = theText_$name;
	else editBody_$name.value += theText_$name;
	editBody_$name.focus();
}

function AddText_$name(wrap_$name, wrap2_$name) {
	if (editBody_$name.curPos) insertText_$name('[' + wrap_$name + ']' + editBody_$name.curPos.text + '[/' + wrap2_$name + ']');
	else insertText_$name('[' + wrap_$name + '][/' + wrap2_$name + ']');
}
function updatePos(obj) {
	if (obj.createTextRange) obj.curPos = document.selection.createRange().duplicate();
}
</script>";
	return $script;
}


// $case ("комментарий", "комментария", "комментариев")

function count_smth ($cnt, $case) 
{	
	(strlen($cnt) == 1) 
		? $minus = 1 
		: $minus = 2;

	$temp1 = substr($cnt, strlen($cnt)-$minus, strlen($cnt));
	$temp2 = substr($cnt, strlen($cnt)-2, strlen($cnt));

	if ($cnt == 0) 
		$count = 'нет '.$case[2];
	elseif ($temp2 == 11 || $temp2 == 12 || $temp2 == 13 || $temp2 == 14) 
		$count = $cnt.' '.$case[2];
	elseif ($cnt == 1) 
		$count = '1 '.$case[0];
	elseif ($temp1 == 2 || $temp1 == 3 || $temp1 == 4) 
		$count = $cnt.' '.$case[1];
	else 
		$count = $cnt.' '.$case[2];
	
	// Фиксим фразу нет минут		
	if ($cnt == 0 && ($case[2] == 'минут назад' || $case[2] == 'секунд назад') ) 
		$count = 'только что';
	
	return $count;

}

function count_smth2 ($cnt, $case) 
{	
	(strlen($cnt) == 1) 
		? $minus = 1 
		: $minus = 2;
		
	$temp1 = substr($cnt, strlen($cnt)-$minus, strlen($cnt));
	$temp2 = substr($cnt, strlen($cnt)-2, strlen($cnt));


	if ($cnt == 0) 
		$count = 'нет '.$case[2];
	elseif ($temp2 == 11 || $temp2 == 12 || $temp2 == 13 || $temp2 == 14) 
		$count = $case[2];
	elseif ($cnt == 1) 
		$count = $case[0];
	elseif ($temp1 == 2 || $temp1 == 3 || $temp1 == 4) 
		$count = $case[1];
	else 
		$count = $case[2];

	// Фиксим фразу нет минут		
	if ($cnt == 0 && ($case[2] == 'минут' || $case[2] == 'секунд') ) 
		$count = 'только что';
	
	return $count;

}


function send_mail ($to, $subject, $message) 
{
	global $SITE;
	// add headers for utf-8 message
	$headers = "From: ".$SITE['site_name']." <".$SITE['site_email'].">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=utf-8\r\n";
	$headers .= "Content-Transfer-Encoding: 8bit\r\n";

	return(@mail ("$to", "$subject", "$message", "$headers"));
}


function myErrorHandler($errno, $errmsg, $filename, $linenum, $vars) {
	global $SITE;
	
    $errortype = array (
                1		=> 'Error',
                2		=> 'Warning',
                4		=> 'Parsing Error',
                8		=> 'Notice',
                16      => 'Core Error',
                32    	=> 'Core Warning',
                64   	=> 'Compile Error',
                128		=> 'Compile Warning',
                256		=> 'User Error',
                512		=> 'User Warning',
                1024	=> 'User Notice',
                2047	=> 'All',
                2048	=> 'Runtime Notice'
                );
	$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);


	$dt = date('Y-m-d H:i:s');
	$myip=getenv('REMOTE_ADDR');
	$err = '<error>\r\n';
	$err .= '<date>' . $dt . '</date>\r\n';
	$err .= '<ip>' . $myip . '</ip>\r\n';
	$err .= '<errno>' . $errno . '</errno>\r\n';
	$err .= '<type>' . $errortype[$errno] . '</type>\r\n';
	$err .= '<msg>' . $errmsg . '</msg>\r\n';
	$err .= '<script>' . $filename . '</script>\r\n';
	$err .= '<line>' . $linenum . '</line>\r\n';
	$err .= '</error>\r\n';
	
	if ($errno != 8 && $errno != 2048) 
	{
		log_error($err);
		error_500 ();
	}

}



function log_error($message) 
{
	global $SITE;

    $f=fopen($_SERVER['DOCUMENT_ROOT'].'/engine/errorlog.txt','a+');
    fwrite($f,$message);
    fclose($f);
	
	send_mail($SITE['site_email'], 'Ошибка на портале '.$SITE['site_name'], 'Error Log: ' . $_SERVER['HTTP_HOST']. $message);
}

function error_404 () 
{
	header ('HTTP/1.0 404 Not Found');
	ob_end_clean ();
	include $_SERVER['DOCUMENT_ROOT'].'/404.html';
	exit;
}

function error_403 () 
{
	header ('HTTP/1.0 403 Forbidden');
	ob_end_clean ();
	include $_SERVER['DOCUMENT_ROOT'].'/403.html';
	exit;
}

function error_500 () 
{
	header ('HTTP/1.0 500 Integral Server Error');
	ob_end_clean ();
	include $_SERVER['DOCUMENT_ROOT'].'/500.html';
	exit;
}

